package indi.lqzhi.basic.ui.basic;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.SparseArray;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import androidx.annotation.IdRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;

import com.blankj.utilcode.util.KeyboardUtils;

import java.util.Random;

import indi.lqzhi.basic.BasicApp;
import indi.lqzhi.basic.ui.basic.action.ClickAction;
import indi.lqzhi.basic.ui.basic.action.HandlerAction;
import indi.lqzhi.basic.ui.basic.action.LogAction;

public abstract class BaseActivity<Bind extends ViewDataBinding> extends AppCompatActivity implements ClickAction, Handler.Callback, HandlerAction, LogAction {

    protected Bind bindView;

    protected Handler handler = new Handler(Looper.myLooper(), this);

    public String TAG = getClass().getSimpleName();

    /** Activity 回调集合 */
    protected SparseArray<OnActivityCallback> mActivityCallbacks;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bindView = DataBindingUtil.setContentView(this, getLayoutId());
        //初始化Activity
        initAcivity();
        //隐藏输入法
        KeyboardUtils.hideSoftInput(this);//隐藏软输入法
    }

    @LayoutRes
    public abstract int getLayoutId();

    protected abstract void initAcivity();


    //点击外部自动隐藏输入法
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                KeyboardUtils.hideSoftInput(this);//隐藏软输入法
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    // 返回点击的组件
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if ((v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationOnScreen(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            return !(event.getRawX() > left && event.getRawX() < right
                    && event.getRawY() > top && event.getRawY() < bottom);
        }
        return false;
    }

    @Override
    public void finish() {
        KeyboardUtils.hideSoftInput(this);//隐藏软输入法
        super.finish();
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
        // 隐藏软键，避免内存泄漏
        KeyboardUtils.hideSoftInput(this);//隐藏软输入法
        // 查看源码得知 startActivity 最终也会调用 startActivityForResult
        super.startActivityForResult(intent, requestCode, options);
    }

    /**
     * startActivityForResult 方法优化
     */
    public void startActivityForResult(Class<? extends Activity> clazz, OnActivityCallback callback) {
        startActivityForResult(new Intent(this, clazz), null, callback);
    }

    public void startActivityForResult(Intent intent, OnActivityCallback callback) {
        startActivityForResult(intent, null, callback);
    }

    public void startActivityForResult(Intent intent, @Nullable Bundle options, OnActivityCallback callback) {
        if (mActivityCallbacks == null) {
            mActivityCallbacks = new SparseArray<>(1);
        }
        // 请求码必须在 2 的 16 次方以内
        int requestCode = new Random().nextInt((int) Math.pow(2, 16));
        mActivityCallbacks.put(requestCode, callback);
        startActivityForResult(intent, requestCode, options);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        OnActivityCallback callback;
        if (mActivityCallbacks != null && (callback = mActivityCallbacks.get(requestCode)) != null) {
            callback.onActivityResult(resultCode, data);
            mActivityCallbacks.remove(requestCode);
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public interface OnActivityCallback {

        /**
         * 结果回调
         *
         * @param resultCode        结果码
         * @param data              数据
         */
        void onActivityResult(int resultCode, @Nullable Intent data);
    }

    @Override
    protected void onDestroy() {
        removeCallbacks();
        super.onDestroy();
    }

    /**
     * 获取 Handler
     */
    @Override
    public Handler getHandler() {
        return handler;
    }

    @Override
    public boolean handleMessage(@NonNull Message msg) {
        //交给子类完成
        return false;
    }

    @Override
    public boolean isDebug() {
        return BasicApp.isDebug();
    }

    /**
     * 跳转到其它Activity的方法
     */
    protected void startActivity(Class<? extends AppCompatActivity> aClass){
        startActivity(new Intent(this,aClass));
        //overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }

    /**
     * 跳转到其它Activity的方法
     */
    protected void startActivity(Class<? extends AppCompatActivity> aClass,Bundle bundle){
        startActivity(new Intent(this,aClass),bundle);
        //overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }

    /**
     * 跳转到其它Activity的方法
     */
    protected void startActivity(Class<? extends AppCompatActivity> aClass,int requestCode){
        startActivityForResult(new Intent(this,aClass),requestCode);
        //overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }

    /**
     * 跳转到其它Activity的方法
     */
    protected void startActivity(Class<? extends AppCompatActivity> aClass,int requestCode,Bundle bundle){
        startActivityForResult(new Intent(this,aClass),requestCode,bundle);
        //overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }

    /**
     * 帮findViewById改个名字,顺便优化一下，当绑定异常时，抛出空指针异常
     * @param id 资源的ID
     * @param <T> View的子类
     * @return 绑定的View
     */
    protected <T extends View> T bindView(@IdRes int id){
        T t = super.findViewById(id);
        if (t == null){
            throw new NullPointerException("resource id "+ id +" not find! findViewById error!");
        }
        return t;
    }

    public String getTAG(){
        return TAG;
    }

    protected View getRootView() {
        return ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);
    }

    //    @Override
//    protected void attachBaseContext(Context newBase) {
//        //注入字体
//        super.attachBaseContext(ViewPumpContextWrapper.wrap(newBase));
//    }

}
